const ip = "https://www.liaohejiandu.cn/";
// const ip = "https://127.0.0.1:8443/";
const appid = "wxdad590a9efc61c8c";
const url = {
  jscode2session: ip + 'wechat/jscode2session',
  wxAccessToken: ip + 'wechat/wxAccessToken',
  isBound: ip + 'lhjd/user/isBound',
  tokenUrl: ip + "wechat/login",
  infoUrl: ip + 'lhjd/user/getInfo',
  listUserByRoleKey: ip + 'lhjd/user/listUserByRoleKey',
  listRoleByUserId: ip + 'lhjd/user/listRoleByUserId',
  examine: ip + 'lhjd/examine',
  examineList: ip + 'lhjd/examine/list',
  xckhbList: ip + 'lhjd/xckhb/list',
  xckhb: ip + 'lhjd/xckhb',
  zhkhbList: ip + 'lhjd/zhkhb/list',
  zhkhb: ip + 'lhjd/zhkhb',
  fhfbbList: ip + 'lhjd/fhfbb/list',
  fhfbb: ip + 'lhjd/fhfbb',
  ldjlbList: ip + 'lhjd/ldjlb/list',
  ldjlb: ip + 'lhjd/ldjlb',
  jkaqList: ip + 'lhjd/jkaq/list',
  jkaq: ip + 'lhjd/jkaq',
  kscjList: ip + 'lhjd/kscj/list',
  kscj: ip + 'lhjd/kscj',
  jdhpbList: ip + 'lhjd/jdhpb/list',
  jdhpb: ip + 'lhjd/jdhpb',
  sgdwpfbList: ip + 'lhjd/sgdwpfb/list',
  sgdwpfb: ip + 'lhjd/sgdwpfb',
  wtmxbList: ip + 'lhjd/wtmxb/list',
  wtmxb: ip + 'lhjd/wtmxb',
  zgdList: ip + 'lhjd/wtmxb/zgdList',
  gcfkbList: ip + 'lhjd/gcfkb/list',
  gcfkb: ip + 'lhjd/gcfkb',
  fkdList: ip + 'lhjd/fkd/list',
  importXls: ip + 'excel/data/upload',
  examineList: ip + 'lhjd/examine/list',
  totalList: ip + 'lhjd/total/list',
  ljcyList: ip + 'lhjd/ljcy/list',
  ljcy: ip + 'lhjd/ljcy',
  jbfsList: ip + 'lhjd/jbfs/list',
  jbfs: ip + 'lhjd/jbfs',
  bound: ip + 'lhjd/user/bound',
  base64Img: ip + 'minio/base64img',
  upload: ip + 'minio/upload',
  user: ip + 'lhjd/user',
  wechatUser: ip + 'wechat/user',
  wechatUserList: ip + 'wechat/user/list',
  listDic: ip + 'system/dict/data/list',
  //录井监督
  xcgl: ip + 'ljjd/xcgl',
  xcglList: ip + 'ljjd/xcgl/list',
  zhkh: ip + 'ljjd/zhkh',
  zhkhList: ip + 'ljjd/zhkh/list',
  ldjl: ip + 'ljjd/ldjl',
  ldjlList: ip + 'ljjd/ldjl/list',
  jdhp: ip + 'ljjd/jdhp',
  jdhpList: ip + 'ljjd/jdhp/list',
  sgdwpf: ip + 'ljjd/sgdwpf',
  sgdwpfList: ip + 'ljjd/sgdwpf/list',
  wtmx: ip + 'ljjd/wtmx',
  wtmxList: ip + 'ljjd/wtmx/list',
  gcfk: ip + 'ljjd/gcfk',
  gcfkList: ip + 'ljjd/gcfk/list',
  ljjd: {
    xcglList: ip + 'ljjd/xcgl/list',
    zhkhList: ip + 'ljjd/zhkh/list',
    ldjlList: ip + 'ljjd/ldjl/list',
    jdhpList: ip + 'ljjd/jdhp/list',
    sgdwpfList: ip + 'ljjd/sgdwpf/list',
    wtmxList: ip + 'ljjd/wtmx/list',
    gcfkList: ip + 'ljjd/gcfk/list',
    totalList: ip + 'ljjd/total/list'
  },
  zjjd: {
    xcgl: ip + 'zjjd/xcgl',
    xcglList: ip + 'zjjd/xcgl/list',
    zhkh: ip + 'zjjd/zhkh',
    zhkhList: ip + 'zjjd/zhkh/list',
    fhfb: ip + 'zjjd/fhfb',
    fhfbList: ip + 'zjjd/fhfb/list',
    ldjl: ip + 'zjjd/ldjl',
    ldjlList: ip + 'zjjd/ldjl/list',
    jdhp: ip + 'zjjd/jdhp',
    jdhpList: ip + 'zjjd/jdhp/list',
    sgdwpf: ip + 'zjjd/sgdwpf',
    sgdwpfList: ip + 'zjjd/sgdwpf/list',
    wtmx: ip + 'zjjd/wtmx',
    wtmxList: ip + 'zjjd/wtmx/list',
    zgdList: ip + 'zjjd/zgd/zgdList',
    gcfk: ip + 'zjjd/gcfk',
    gcfkList: ip + 'zjjd/gcfk/list',
    totalList: ip + 'zjjd/total/list',
    exportAll: ip + 'zjjd/total/export' 
  }
};

module.exports = {
  ip: ip,
  appid: appid,
  url: url,
  getDicIndex,
  getDic,
  get,
  post,
  put,
  del,
  getCurrUserInfo,
  syncCurrUser,
  getSysUser,
  getPermissions,
  getToken,
  syncToken,
  hasPerm,
  preBase64ImgList,
  preBase64Img,
  getCurrentMonthFirst,
  getCurrentMonthLast,
  isBlank,
  isNumber,
  isObject,
  isArray,
  isBoolean,
  isString,
  sleep,
  rinse,
  uploadFile,
  back,
  chain,
  addRefresh,
  isRefresh,
  refresh,
  page,
  listRoles
}

function getCurrUserInfo() {
  let userInfo = wx.getStorageSync('sysUserInfo');
  if (userInfo != null && userInfo != undefined && userInfo != '') {
    return userInfo;
  }
  let openid = wx.getStorageSync('openid');
  syncCurrUser(openid).then(res => {
    return res;
  });
}

function syncCurrUser(openid) {
  if (!isBlank(openid)) {
    wx.setStorageSync('openid', openid);
  }
  return new Promise((resolve, reject) => {
    syncToken().then(res => {
      get(url.infoUrl).then(res => {
        wx.setStorageSync('sysUserInfo', res);
        resolve(res.user);
      })
    });
  });
}

function getSysUser() {
  return getCurrUserInfo().user;
}

function getPermissions() {
  return getCurrUserInfo().permissions;
}

function getToken() {
  let lastTime = wx.getStorageSync('token_lastTime');
  let currTime = new Date();
  let l = currTime - lastTime;
  let token = wx.getStorageSync('token');
  if (l / 1000 / 60 > 20 ||
    (lastTime == null || lastTime == undefined || lastTime == '') ||
    (token == null || token == undefined || token == '')) {
    syncToken();
  }

  return token;
}

function syncToken() {
  return new Promise((resolve, reject) => {
    wx.request({
      url: url.tokenUrl,
      data: {
        appid: appid,
        openid: wx.getStorageSync('openid')
      },
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.code === 200) { //请求成功
          wx.setStorageSync('token', res.data.token);
          wx.setStorageSync('token_lastTime', new Date());
          resolve(res.data)
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      },
      fail: function (res) {
        console.error(res);
      }
    })
  })
}

function hasPerm(permStr) {
  var flag = false;
  getPermissions().forEach(function (item) {
    if (item == permStr) {
      flag = true;
    }
  });
  return flag;
}

function preBase64ImgList(picList, callback) {
  var totalImgSize = 0;
  var completeImgSize = 0;
  var imgMap = {};
  if (isBlank(picList)) {
    callback(imgMap);
    return;
  }
  picList.forEach(function (item) {
    totalImgSize++;
    preBase64Img(item, function (map) {
      completeImgSize++;
      Object.keys(map).forEach(function (img) {
        imgMap[img] = map[img];
      });
      if (totalImgSize == completeImgSize) {
        callback(imgMap);
      }
    });
  });
}

function preBase64Img(pic, callback) {
  if (!isBlank(pic)) {
    var totalImgSize = 0;
    var completeImgSize = 0;
    var imgMap = {};
    var imgs = pic.split(',');
    imgs.forEach(function (img) {
      totalImgSize++;
      get(url.base64Img, {
        fileId: img
      }).then(res => {
        if (res.code === 200) { //请求成功
          completeImgSize++;
          imgMap[img] = res.data;
          if (totalImgSize == completeImgSize) {
            callback(imgMap);
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      });
    });
  }
}

function uploadFile(tempFilePaths, workId, callback) {
  var totalImgSize = 0;
  var completeImgSize = 0;
  var results = [];
  tempFilePaths.forEach(function (tempFilePath) {
    totalImgSize++;
    wx.uploadFile({
      url: url.upload,
      filePath: tempFilePath,
      name: 'file',
      formData: {
        workId: workId
      },
      header: {
        'Authorization': getToken(),
      },
      success(res) {
        var data = JSON.parse(res.data);
        if (data.code === 200) { //请求成功
          completeImgSize++;
          results.push(data.data);
          if (totalImgSize == completeImgSize) {
            callback(results);
          }
        } else {
          wx.showToast({
            title: data.msg,
            icon: 'none'
          })
        }
      },
      fail(res) {
        console.error(res);
      }
    })
  });
}

function back(title, icon) {
  wx.showToast({
    title: title,
    icon: icon
  })
  setTimeout(function () {
    var delta = 1;
    var len = getCurrentPages().length;
    var index = len - 1 - delta;
    var route = getCurrentPages()[index].route;
    addRefresh(route);
    wx.navigateBack({
      delta: delta,
    })
  }, 1500);
}

function addRefresh(route) {
  var refreshs = getApp().globalData.refreshs;
  if (isBlank(refreshs)) {
    getApp().globalData.refreshs = [];
  }
  getApp().globalData.refreshs.push(route);
}

function refresh(options, callback) {
  if (!isRefresh()) {
    return;
  }
  var len = getCurrentPages().length;
  var route = getCurrentPages()[len - 1].route;
  var refreshs = getApp().globalData.refreshs;
  var newRefreshs = [];
  refreshs.forEach(function (rt) {
    if (rt != route) {
      newRefreshs.push(rt);
    }
  });
  getApp().globalData.refreshs = newRefreshs;
  callback(options);
}

function isRefresh() {
  var len = getCurrentPages().length;
  var route = getCurrentPages()[len - 1].route;
  var refreshs = getApp().globalData.refreshs;
  if (isBlank(refreshs)) {
    return false;
  }
  var flag = false;
  refreshs.forEach(function (rt) {
    if (rt == route) {
      flag = true;
    }
  });
  return flag;
}

function chain(params) {
  let chain = getApp().globalData.chain;
  let pages = getCurrentPages();
  let length = pages.length;
  if (isObject(params) && Object.keys(params).length == 0) {
    let page = pages[length - 1];
    chain[page.__route__] = {};
  } else if (isBlank(params)) {
    let pm = {};
    let new_chain = {};
    pages.forEach((page) => {
      let v = chain[page.__route__];
      if (!isBlank(v)) {
        pm = {
          ...pm,
          ...v
        };
        new_chain[page.__route__] = v;
      }
    });
    chain = {
      ...new_chain
    };
    return pm;
  } else if (isNumber(params)) {
    let page = pages[length - 1 + params];
    return chain[page.__route__];
  } else if (isObject(params)) {
    let page = pages[length - 1];
    let old = chain[page.__route__];
    if (isBlank(old)) {
      old = {};
    }
    return chain[page.__route__] = {
      ...old,
      ...params
    }
  } else {
    return chain[params];
  }
}

function page(pageSize) {
  return {
    pageNum: 1,
    pageSize: pageSize,
    total: 100,
    totalPage: 1,
    setTotal(total) {
      if (total == null || total == "") {
        this.totalPage = 0;
      } else {
        if (this.pageSize != 0 && total % this.pageSize == 0) {
          this.totalPage = parseInt(total / this.pageSize);
        }
        if (this.pageSize != 0 && total % this.pageSize != 0) {
          this.totalPage = parseInt(total / this.pageSize) + 1;
        }
      }
      this.pageNum = this.pageNum + 1;
      this.total = total;
    }
  };
}

function request(url, options) {
  return new Promise((resolve, reject) => {
    let header = {
      'content-type': 'application/x-www-form-urlencoded'
    }
    if (isBlank(options.noAuth) || options.noAuth != true) {
      header.Authorization = getToken()
    }
    wx.request({
      url: url,
      method: options.method,
      data: options.data,
      header: header,
      success(request) {
        if (request.data.code === 200) { //请求成功
          resolve(request.data)
        } else if (request.data.status == 403) {
          wx.showToast({
            title: '清除缓存后再试',
            icon: 'none',
            duration: 2000
          })
        } else {
          //reject(request.data)
          wx.showToast({
            title: request.data.msg,
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail(error) {
        //reject(error.data)
        wx.showToast({
          title: error.data.msg,
          icon: 'none'
        })
      }
    })
  })
}

function get(url, options = {}, page) {
  options = rinse(options);
  if (page) {
    if (page.pageNum > page.totalPage) {
      return new Promise((resolve, reject) => {
        resolve({
          rows: []
        })
      });
    }
    options.pageNum = page.pageNum;
    options.pageSize = page.pageSize;
  }
  let isShow = false;
  let tmot = setTimeout(function () {
    isShow = true;
    wx.showLoading({
      title: '',
      icon: 'loading'
    });
  }, 1000);
  let _noAuth = false;
  if (!isBlank(options) && !isBlank(options._noAuth)) {
    _noAuth = options._noAuth;
    delete options._noAuth;
  }
  let result = request(url, {
    method: 'GET',
    data: options,
    noAuth: _noAuth
  });
  clearTimeout(tmot);
  if (isShow) {
    wx.hideLoading();
  }
  wx.stopPullDownRefresh();
  return result;
}

function post(url, options) {
  let _noAuth = false;
  if (!isBlank(options) && !isBlank(options._noAuth)) {
    _noAuth = options._noAuth;
    delete options._noAuth;
  }
  return request(url, {
    method: 'POST',
    data: options,
    noAuth: _noAuth
  })
}

function put(url, options) {
  let _noAuth = false;
  if (!isBlank(options) && !isBlank(options._noAuth)) {
    _noAuth = options._noAuth;
    delete options._noAuth;
  }
  return request(url, {
    method: 'PUT',
    data: options,
    noAuth: _noAuth
  })
}

function del(url, options) {
  let _noAuth = false;
  if (!isBlank(options) && !isBlank(options._noAuth)) {
    _noAuth = options._noAuth;
    delete options._noAuth;
  }
  return request(url, {
    method: 'DELETE',
    data: options,
    noAuth: _noAuth
  })
}

function getCurrentMonthFirst() {
  var date = new Date();
  date.setDate(1);
  var month = parseInt(date.getMonth() + 1);
  var day = date.getDate();
  if (month < 10) {
    month = '0' + month
  }
  if (day < 10) {
    day = '0' + day
  }
  return date.getFullYear() + '-' + month + '-' + day;
}

function getCurrentMonthLast() {
  var date = new Date();
  var currentMonth = date.getMonth();
  var nextMonth = ++currentMonth;
  var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
  var oneDay = 1000 * 60 * 60 * 24;
  var lastTime = new Date(nextMonthFirstDay - oneDay);
  var month = parseInt(lastTime.getMonth() + 1);
  var day = lastTime.getDate();
  if (month < 10) {
    month = '0' + month
  }
  if (day < 10) {
    day = '0' + day
  }
  return date.getFullYear() + '-' + month + '-' + day;
}

function sleep(time) {
  for (var t = Date.now(); Date.now() - t <= time;);
}

function rinse(obj) {
  Object.keys(obj).forEach(key => {
    if (isBlank(obj[key])) {
      delete obj[key];
    }
  });
  return obj;
}

function isBlank(obj) {
  if (isNumber(obj)) {
    return false;
  }
  if (isBoolean(obj)) {
    return false;
  }
  if (obj == null || obj == undefined || obj == "" || obj == NaN) {
    return true;
  }
  if (obj.length == 0) {
    return true;
  }
  if (Object.keys(obj).length == 0) {
    return true;
  }
  return false;
}

/**
 * 校验只要是数字（包含正负整数，0以及正负浮点数）就返回true
 **/
function isNumber(obj) {
  var type = Object.prototype.toString.call(obj);
  return type == '[object Number]';
}

function isObject(obj) {
  var type = Object.prototype.toString.call(obj);
  return type == '[object Object]';
}

function isArray(obj) {
  var type = Object.prototype.toString.call(obj);
  return type == '[object Array]';
}

function isBoolean(obj) {
  var type = Object.prototype.toString.call(obj);
  return type == '[object Boolean]';
}

function isString(obj) {
  var type = Object.prototype.toString.call(obj);
  return type == '[object String]';
}

function getDicIndex(value, dic, valueName) {
  if (isBlank(valueName)) {
    valueName = 'dictValue';
  }
  for (var i = 0; i < dic.length; i++) {
    if (dic[i][valueName] == value) {
      return i;
    }
  }
}

async function getDic(dictType) {
  let res = await get(url.listDic, {
    dictType: dictType
  });
  return res.rows;
}

async function listRoles() {
  let res = await get(url.listRoleByUserId, {
    userId: getSysUser().userId
  });
  let list = [];
  res.rows.forEach(item => {
    list.push({
      value: item.roleKey,
      label: item.roleName
    });
  });
  return list;
}

/**  
 * 日期格式化  
 * 格式 YYYY/yyyy/YY/yy 表示年份  
 * MM/M 月份  
 * W/w 星期  
 * dd/DD/d/D 日期  
 * hh/HH/h/H 时间  
 * mm/m 分钟  
 * ss/SS/s/S 秒  
 */
Date.prototype.format = function (formatStr) {
  var str = formatStr;
  var Week = ['日', '一', '二', '三', '四', '五', '六'];

  str = str.replace(/yyyy|YYYY/, this.getFullYear());
  str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));

  str = str.replace(/MM/, this.getMonth() > 9 ? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1));
  str = str.replace(/M/g, this.getMonth());

  str = str.replace(/w|W/g, Week[this.getDay()]);

  str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
  str = str.replace(/d|D/g, this.getDate());

  str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
  str = str.replace(/h|H/g, this.getHours());
  str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
  str = str.replace(/m/g, this.getMinutes());

  str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
  str = str.replace(/s|S/g, this.getSeconds());

  return str;
};